import { ref, watch } from 'vue'
import { requestErrorHandler } from '@/errorHandler'

const MIN_REQUEST_INTERVAL = 1500

export default function useApiCallback(fn, options = {}) {
  const loading = ref(false)
  const status = ref('try')
  const isDelay = ref(false)

  async function handleRequest() {
    try {
      status.value = 'try'
      if (loading.value) return
      loading.value = true
      isDelay.value = true
      return await fn.call(this, ...arguments)
    } catch (err) {
      status.value = 'catch'
      requestErrorHandler(err)
      return err
    } finally {
      status.value = 'finally'
      if (!isDelay.value) {
        loading.value = false
      }
    }
  }

  watch(isDelay, (newVal) => {
    if (!newVal) return
    setTimeout(() => {
      isDelay.value = false
      if (status.value === 'finally') {
        loading.value = false
      }
    }, options.requestInterval || MIN_REQUEST_INTERVAL)
  })

  return [handleRequest, loading]
}